import React, { useState } from 'react'
import { Card, Table, Button, Modal, Form, Input, Select, Steps, Space, Tag, message, Timeline, Progress } from 'antd'
import { PlusOutlined, EditOutlined, DeleteOutlined, PlayCircleOutlined, PauseCircleOutlined } from '@ant-design/icons'
import Layout from '../components/Layout/Layout'

const { Option } = Select
const { TextArea } = Input
const { Step } = Steps

export default function Workflows() {
  const [workflows, setWorkflows] = useState([
    {
      id: 1,
      name: '设备维护流程',
      description: '设备故障报修到维护完成的完整流程',
      status: 'active',
      steps: [
        { name: '故障报告', assignee: '设备管理员', status: 'completed' },
        { name: '问题评估', assignee: '技术主管', status: 'completed' },
        { name: '维护执行', assignee: '维护工程师', status: 'in_progress' },
        { name: '测试验收', assignee: '质量检查员', status: 'pending' },
        { name: '完成归档', assignee: '设备管理员', status: 'pending' }
      ],
      currentStep: 2,
      createdDate: '2024-01-10',
      completedCount: 15,
      totalCount: 18
    },
    {
      id: 2,
      name: '访客审批流程',
      description: '外部访客进入园区的审批流程',
      status: 'active',
      steps: [
        { name: '访客申请', assignee: '接待人员', status: 'completed' },
        { name: '安全审核', assignee: '安全主管', status: 'completed' },
        { name: '领导批准', assignee: '部门经理', status: 'completed' },
        { name: '通行证发放', assignee: '前台', status: 'pending' }
      ],
      currentStep: 3,
      createdDate: '2024-01-08',
      completedCount: 23,
      totalCount: 25
    }
  ])

  const [instances, setInstances] = useState([
    {
      id: 1,
      workflowId: 1,
      workflowName: '设备维护流程',
      title: 'A区空调故障维修',
      initiator: '张三',
      currentStep: 2,
      status: 'in_progress',
      createdDate: '2024-01-15 09:00',
      dueDate: '2024-01-17 18:00',
      priority: 'high'
    },
    {
      id: 2,
      workflowId: 2,
      workflowName: '访客审批流程',
      title: '科技公司商务访问',
      initiator: '李四',
      currentStep: 1,
      status: 'pending',
      createdDate: '2024-01-15 14:30',
      dueDate: '2024-01-16 10:00',
      priority: 'medium'
    }
  ])

  const [activeTab, setActiveTab] = useState('workflows')
  const [modalVisible, setModalVisible] = useState(false)
  const [instanceModalVisible, setInstanceModalVisible] = useState(false)
  const [editingRecord, setEditingRecord] = useState(null)
  const [selectedWorkflow, setSelectedWorkflow] = useState(null)
  const [form] = Form.useForm()
  const [instanceForm] = Form.useForm()

  const statusColors = {
    active: 'green',
    inactive: 'gray',
    draft: 'orange'
  }

  const statusTexts = {
    active: '活跃',
    inactive: '停用',
    draft: '草稿'
  }

  const instanceStatusColors = {
    pending: 'orange',
    in_progress: 'blue',
    completed: 'green',
    rejected: 'red',
    cancelled: 'gray'
  }

  const instanceStatusTexts = {
    pending: '待处理',
    in_progress: '进行中',
    completed: '已完成',
    rejected: '已拒绝',
    cancelled: '已取消'
  }

  const priorityColors = {
    high: 'red',
    medium: 'orange',
    low: 'blue'
  }

  const priorityTexts = {
    high: '高',
    medium: '中',
    low: '低'
  }

  const workflowColumns = [
    {
      title: '流程名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '状态',
      key: 'status',
      render: (_, record) => (
        <Tag color={statusColors[record.status]}>
          {statusTexts[record.status]}
        </Tag>
      ),
    },
    {
      title: '步骤数',
      key: 'steps',
      render: (_, record) => `${record.steps.length} 步`,
    },
    {
      title: '完成率',
      key: 'completion',
      render: (_, record) => (
        <div>
          <Progress 
            percent={Math.round((record.completedCount / record.totalCount) * 100)}
            size="small"
          />
          <div style={{ fontSize: 12, color: '#666' }}>
            {record.completedCount}/{record.totalCount}
          </div>
        </div>
      ),
    },
    {
      title: '创建日期',
      dataIndex: 'createdDate',
      key: 'createdDate',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="link" 
            icon={<PlayCircleOutlined />}
            onClick={() => handleStartInstance(record)}
          >
            启动
          </Button>
          <Button 
            type="link" 
            icon={<EditOutlined />}
            onClick={() => handleEditWorkflow(record)}
          >
            编辑
          </Button>
          <Button 
            type="link" 
            danger 
            icon={<DeleteOutlined />}
            onClick={() => handleDeleteWorkflow(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ]

  const instanceColumns = [
    {
      title: '实例标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '流程名称',
      dataIndex: 'workflowName',
      key: 'workflowName',
    },
    {
      title: '发起人',
      dataIndex: 'initiator',
      key: 'initiator',
    },
    {
      title: '当前步骤',
      key: 'currentStep',
      render: (_, record) => {
        const workflow = workflows.find(w => w.id === record.workflowId)
        const stepName = workflow?.steps[record.currentStep]?.name || '未知'
        return `第${record.currentStep + 1}步: ${stepName}`
      },
    },
    {
      title: '状态',
      key: 'status',
      render: (_, record) => (
        <Tag color={instanceStatusColors[record.status]}>
          {instanceStatusTexts[record.status]}
        </Tag>
      ),
    },
    {
      title: '优先级',
      key: 'priority',
      render: (_, record) => (
        <Tag color={priorityColors[record.priority]}>
          {priorityTexts[record.priority]}
        </Tag>
      ),
    },
    {
      title: '截止时间',
      dataIndex: 'dueDate',
      key: 'dueDate',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="link"
            onClick={() => handleViewInstance(record)}
          >
            查看详情
          </Button>
          <Button 
            type="link" 
            icon={<EditOutlined />}
            onClick={() => handleEditInstance(record)}
          >
            编辑
          </Button>
        </Space>
      ),
    },
  ]

  const handleStartInstance = (workflow) => {
    setSelectedWorkflow(workflow)
    instanceForm.setFieldsValue({ workflowId: workflow.id })
    setInstanceModalVisible(true)
  }

  const handleEditWorkflow = (record) => {
    setEditingRecord(record)
    form.setFieldsValue(record)
    setModalVisible(true)
  }
  
  const handleDeleteWorkflow = (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确认删除这个工作流吗？',
      onOk: () => {
        setWorkflows(prev => prev.filter(item => item.id !== id))
        message.success('删除成功')
      }
    })
  }

  const handleViewInstance = (record) => {
    const workflow = workflows.find(w => w.id === record.workflowId)
    Modal.info({
      title: '流程实例详情',
      width: 800,
      content: (
        <div style={{ marginTop: 16 }}>
          <div style={{ marginBottom: 24 }}>
            <h4>基本信息</h4>
            <div>标题: {record.title}</div>
            <div>发起人: {record.initiator}</div>
            <div>创建时间: {record.createdDate}</div>
            <div>截止时间: {record.dueDate}</div>
          </div>
          
          <div style={{ marginBottom: 24 }}>
            <h4>流程进度</h4>
            <Steps current={record.currentStep} size="small">
              {workflow?.steps.map((step, index) => (
                <Step 
                  key={index}
                  title={step.name}
                  description={step.assignee}
                />
              ))}
            </Steps>
          </div>

          <div>
            <h4>处理历史</h4>
            <Timeline size="small">
              <Timeline.Item color="green">
                <div>流程启动</div>
                <div style={{ fontSize: 12, color: '#666' }}>
                  {record.createdDate} - {record.initiator}
                </div>
              </Timeline.Item>
              <Timeline.Item color="blue">
                <div>当前步骤: {workflow?.steps[record.currentStep]?.name}</div>
                <div style={{ fontSize: 12, color: '#666' }}>
                  处理人: {workflow?.steps[record.currentStep]?.assignee}
                </div>
              </Timeline.Item>
            </Timeline>
          </div>
        </div>
      )
    })
  }

  const handleEditInstance = (record) => {
    // 编辑实例逻辑
    message.info('编辑实例功能')
  }

  const handleSubmitWorkflow = async (values) => {
    try {
      if (editingRecord) {
        setWorkflows(prev => 
          prev.map(item => 
            item.id === editingRecord.id ? { ...item, ...values } : item
          )
        )
        message.success('更新成功')
      } else {
        const newWorkflow = {
          id: Date.now(),
          ...values,
          status: 'draft',
          completedCount: 0,
          totalCount: 0,
          createdDate: new Date().toISOString().split('T')[0]
        }
        setWorkflows(prev => [...prev, newWorkflow])
        message.success('创建成功')
      }
      setModalVisible(false)
      form.resetFields()
      setEditingRecord(null)
    } catch (error) {
      message.error('操作失败')
    }
  }

  const handleSubmitInstance = async (values) => {
    try {
      const newInstance = {
        id: Date.now(),
        ...values,
        workflowName: selectedWorkflow?.name || '',
        currentStep: 0,
        status: 'pending',
        createdDate: new Date().toLocaleString(),
      }
      setInstances(prev => [...prev, newInstance])
      message.success('流程实例创建成功')
      setInstanceModalVisible(false)
      instanceForm.resetFields()
      setSelectedWorkflow(null)
    } catch (error) {
      message.error('创建失败')
    }
  }

  return (
    <Layout>
      <div style={{ padding: '24px' }}>
        <Card 
          title="工作流管理"
          tabList={[
            { key: 'workflows', tab: '流程定义' },
            { key: 'instances', tab: '流程实例' }
          ]}
          activeTabKey={activeTab}
          onTabChange={setActiveTab}
          extra={
            <Space>
              {activeTab === 'workflows' && (
                <Button 
                  type="primary" 
                  icon={<PlusOutlined />}
                  onClick={() => {
                    setEditingRecord(null)
                    form.resetFields()
                    setModalVisible(true)
                  }}
                >
                  新建流程
                </Button>
              )}
            </Space>
          }
        >
          {activeTab === 'workflows' && (
            <Table
              columns={workflowColumns}
              dataSource={workflows}
              rowKey="id"
              pagination={false}
            />
          )}
          {activeTab === 'instances' && (
            <Table
              columns={instanceColumns}
              dataSource={instances}
              rowKey="id"
              pagination={{
                pageSize: 10,
                showSizeChanger: true,
                showTotal: (total) => `共 ${total} 条记录`
              }}
            />
          )}
        </Card>

        {/* 工作流编辑模态框 */}
        <Modal
          title={editingRecord ? '编辑工作流' : '新建工作流'}
          open={modalVisible}
          onOk={() => form.submit()}
          onCancel={() => setModalVisible(false)}
          width={600}
        >
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSubmitWorkflow}
          >
            <Form.Item name="name" label="流程名称" rules={[{ required: true }]}>
              <Input placeholder="请输入流程名称" />
            </Form.Item>
            <Form.Item name="description" label="流程描述">
              <TextArea rows={3} placeholder="请输入流程描述" />
            </Form.Item>
            <Form.Item name="status" label="状态" rules={[{ required: true }]}>
              <Select placeholder="请选择状态">
                <Option value="draft">草稿</Option>
                <Option value="active">活跃</Option>
                <Option value="inactive">停用</Option>
              </Select>
            </Form.Item>
          </Form>
        </Modal>

        {/* 流程实例创建模态框 */}
        <Modal
          title="启动流程实例"
          open={instanceModalVisible}
          onOk={() => instanceForm.submit()}
          onCancel={() => setInstanceModalVisible(false)}
          width={600}
        >
          <Form
            form={instanceForm}
            layout="vertical"
            onFinish={handleSubmitInstance}
          >
            <Form.Item name="workflowId" label="工作流" style={{ display: 'none' }}>
              <Input />
            </Form.Item>
            <Form.Item name="title" label="实例标题" rules={[{ required: true }]}>
              <Input placeholder="请输入实例标题" />
            </Form.Item>
            <Form.Item name="initiator" label="发起人" rules={[{ required: true }]}>
              <Input placeholder="请输入发起人" />
            </Form.Item>
            <Form.Item name="priority" label="优先级" rules={[{ required: true }]}>
              <Select placeholder="请选择优先级">
                <Option value="low">低</Option>
                <Option value="medium">中</Option>
                <Option value="high">高</Option>
              </Select>
            </Form.Item>
            <Form.Item name="dueDate" label="截止时间" rules={[{ required: true }]}>
              <Input placeholder="请输入截止时间" />
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </Layout>
  )
}
